//
//  HMHandwritingViewController.m
//  HeartMark
//
//  Created by rimi on 2016/11/6.
//  Copyright © 2016年 黄华强. All rights reserved.
//

#import "HMHandwritingViewController.h"
#import "HMMyNoteModel.h"
#import "HMNoteCell.h"
#import "HMMonthCell.h"
#import "HMEditViewController.h"
#import <AVOSCloud/AVOSCloud.h>
#import "HMAlertView.h"

@interface HMHandwritingViewController ()<UITableViewDelegate,UITableViewDataSource>
//表格视图属性
@property (strong,nonatomic) UITableView *handwritingTableView;
//我的笔记模型数组
@property (nonatomic,strong) NSMutableArray *myNoteModelArray;
//编辑按钮
@property (nonatomic,strong) UIButton *editButton;

@property (nonatomic,copy) NSString *objectID;
//整理后的数据数组
@property (nonatomic,strong) NSMutableArray *dictArr;
//日期
@property (nonatomic,strong) NSDate *date;
//月份中文数组
@property (nonatomic,strong) NSArray * monthStrArr;

@end


@implementation HMHandwritingViewController

- (instancetype)init
{
    self = [super init];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(saveMyNote:) name:@"saveMyNoteNotification" object:nil];
    }
    return self;
}

- (void)saveMyNote:(NSNotification *)info {
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:self.dictArr forKey:@"noteDictArray"];
}

//移除通知
-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
     [self setupUI];
    [self loadData];
    
}

- (void)loadData {
    
//    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
//    
//    NSString *isSave = [userDefaults objectForKey:@"noteSaveArr"];
//    if ([isSave isEqualToString:@"YES"])  {
//        NSArray *arr = [userDefaults objectForKey:@"notSaveArray"];
//        for (NSDictionary *dict5 in arr) {
//            AVObject *note = [[AVObject alloc] initWithClassName:@"note"];// 构建对象
//            
//            [note setObject:self.authorName forKey:@"authorName"];//作者姓名
//            [note setObject:self.authorId forKey:@"authorId"];// 设置作者id
//            [note setObject:_editTextView.text forKey:@"content"];// 设置内容
//            [note setObject:_isPublic forKey:@"isPublic"];
//            [note setObject:collectNumber forKey:@"collectNumber"];
//            [note setObject:@"NO" forKey:@"isDelete"];
//        }
//    }
    
    AVUser *user = [AVUser currentUser];
    _objectID = user[@"objectId"];
    
    AVQuery *query = [AVQuery queryWithClassName:@"note"];
    [query whereKey:@"authorId" equalTo:user[@"objectId"]];
    [query orderByAscending:@"updatedAt"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (error) {
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
          NSArray *dictArray = [userDefaults objectForKey:@"noteDictArray"];
            
            NSMutableArray *muDictArr = [NSMutableArray array];
            for (NSDictionary *yearDict in dictArray) {
                NSArray *monthArr = yearDict[@"monthModels"];
                
                NSMutableArray *muMonthArr = [NSMutableArray array];
                for (NSDictionary *monthDict in monthArr) {
                    NSArray *noteArr = monthDict[@"noteModels"];
                    
                    NSMutableArray *muNoteArr = [NSMutableArray arrayWithArray:noteArr];
                    NSString *currentMonth = monthDict[@"month"];
                    NSDictionary *monthDict2 = @{@"isDelop":@YES,@"month":currentMonth,@"noteModels":muNoteArr};
                    [muMonthArr addObject:monthDict2];
                }
                NSString *currentYear = yearDict[@"year"];
                NSDictionary *yearDict2 = @{@"year":currentYear,@"monthModels":muMonthArr};
                [muDictArr addObject:yearDict2];
            }
            
            self.dictArr = muDictArr;
            
            [HMAlertView bottomAlertView:@"网络好像出了点问题？"];
        } else {
            for (AVObject *obj in objects) {
                NSString *isDelete = obj[@"isDelete"];
                
                if ([isDelete isEqualToString:@"YES"]) {
                    continue;
                }
                
                NSDictionary *objDict = @{@"updatedAt":obj[@"updatedAt"],@"content":obj[@"content"],@"objectId":obj[@"objectId"],@"isPublic":obj[@"isPublic"]};
                [self addNote:objDict];
                
            }
            
           
        }
        self.myNoteModelArray = [HMMyNoteModel getMyNoteModelArray:self.dictArr];
        [self.handwritingTableView reloadData];
    }];
    
}


- (void)addNote:(NSDictionary *)objDict {
    
    _date = objDict[@"updatedAt"];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    [formatter setDateFormat:@"MM月dd日 HH:mm"];
    NSString * currentDate = [formatter stringFromDate:_date];
    
    [formatter setDateFormat:@"yyyy"];
    NSString * currentYear = [formatter stringFromDate:_date];
    
    [formatter setDateFormat:@"MM"];
    NSInteger  currentMonths = [[formatter stringFromDate:_date] integerValue];;
    
    NSString * currentMonth = self.monthStrArr[currentMonths];
    
    BOOL hasYears = NO;
    for (NSDictionary *yearDict in self.dictArr) {
        if (yearDict[@"year"] == currentYear) {
            hasYears = YES;
            BOOL hasMonth = NO;
            
            NSMutableArray *monthModel = yearDict[@"monthModels"];
            
            for (NSDictionary *monthDict in monthModel) {
               
                if ([monthDict[@"month"] isEqualToString: currentMonth]) {
                    hasMonth = YES;
                    
                    NSMutableArray *noteArr = monthDict[@"noteModels"];
                    NSDictionary *noteDict = @{@"content":objDict[@"content"],@"time":currentDate,@"noteId":objDict[@"objectId"],@"isPublic":objDict[@"isPublic"]};
                    [noteArr insertObject:noteDict atIndex:0];
                    
                    
                }
            }
            if (!hasMonth) {
                NSDictionary *noteDict = @{@"content":objDict[@"content"],@"time":currentDate,@"noteId":objDict[@"objectId"],@"isPublic":objDict[@"isPublic"]};
                NSMutableArray *noteArr = [NSMutableArray arrayWithObject:noteDict];
                NSDictionary *monthDict = @{@"isDelop":@YES,@"month":currentMonth,@"noteModels":noteArr};
                [monthModel insertObject:monthDict atIndex:0];
                
            }
            
            
        }
    }
    
    if (!hasYears) {
        NSDictionary *noteDict = @{@"content":objDict[@"content"],@"time":currentDate,@"noteId":objDict[@"objectId"],@"isPublic":objDict[@"isPublic"]};
        NSMutableArray *noteArr = [NSMutableArray arrayWithObject:noteDict];
        NSDictionary *monthDict = @{@"isDelop":@YES,@"month":currentMonth,@"noteModels":noteArr};
        NSMutableArray *monthArr = [NSMutableArray arrayWithObject:monthDict];
        NSDictionary *yeardict = @{@"year":currentYear,@"monthModels":monthArr};
        [self.dictArr insertObject:yeardict atIndex:0];
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    MonthsModel *month = [self isMonth:indexPath];
    // 如果点击的是分组，则取当前状态的反并更新数据
    if (month) {
        return NO;
    } else {
        return YES;
    }
    
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    
   
    return UITableViewCellEditingStyleDelete;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NoteModel *noteModel = [self isNote:indexPath];
    HMMyNoteModel *yearModel = [self.myNoteModelArray objectAtIndex:indexPath.section];
    NSInteger index = -1;
    for (MonthsModel *monthModel in yearModel.monthModels) {
        index += 1;
        for (NoteModel *oneNote in monthModel.noteModels) {
            index += 1;
            if (index == indexPath.row) {
                [monthModel.noteModels removeObject:oneNote];
                break;
            }
        }
        
    }
    
    NSInteger section = indexPath.section;
    
    
    NSDictionary *yearDict = self.dictArr[section];
    NSMutableArray *monthDictArr = yearDict[@"monthModels"];
    NSInteger twoIndex = -1;
    for (NSDictionary *monthDict in monthDictArr) {
        twoIndex += 1;
        NSMutableArray *noteDictArr = monthDict[@"noteModels"];
        for (NSDictionary *noteDict in noteDictArr) {
            twoIndex += 1;
            if (twoIndex == indexPath.row) {
                [noteDictArr removeObject:noteDict];
                break;
            }
        }
    }
    
    [self.handwritingTableView reloadData];
    
    
    AVObject *note = [AVObject objectWithClassName:@"note" objectId:noteModel.noteId];
    [note setObject:@"YES" forKey:@"isDelete"];
    [note saveInBackground];
    
    
}

#pragma mark - UI设置相关

- (void)setupUI {
    self.view.backgroundColor = [UIColor whiteColor];
    
    //添加表格视图到view上
    [self.view addSubview:self.handwritingTableView];
    //注册表格视图的cell和组头cell
    [self.handwritingTableView registerClass:[HMMonthCell class] forCellReuseIdentifier:@"monthCell"];
    [self.handwritingTableView registerClass:[HMNoteCell class] forCellReuseIdentifier:@"noteCell"];
    
    [self.handwritingTableView registerClass:[UITableViewHeaderFooterView class] forHeaderFooterViewReuseIdentifier:@"myHead"];
    
    
    
    
}



#pragma mark - 业务逻辑相关方法
//edit按钮回调方法
- (void)editBtnClicked {
    HMEditViewController *editVC = [[HMEditViewController alloc] init];
    
    editVC.authorId = _objectID;
    
    
    editVC.addNote = ^(NSDictionary *obj){
        [self addNote:obj];
        
        self.myNoteModelArray = [HMMyNoteModel getMyNoteModelArray:self.dictArr];
        [self.handwritingTableView reloadData];
    };
    [self.navigationController pushViewController:editVC animated:YES];
}


#pragma mark - 表格视图的代理方法

//设置cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    MonthsModel *month = [self isMonth:indexPath];
    // 如果点击的是分组，则取当前状态的反并更新数据
    if (month) {
        return 44;
    } else {
        return 70;
    }
}

//返回的组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [self.myNoteModelArray count];
}
//不同的section返回不同数量的row
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    HMMyNoteModel *year = [self.myNoteModelArray objectAtIndex:section];
    NSMutableArray *monthArr = year.monthModels;
    NSInteger all = [monthArr count];
    
    for (MonthsModel *month in monthArr) {
        if (month.isDelop) {
            all += [month.noteModels count];
        }
    }
    return all;
}
//根据不同的情况返回不同的cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    MonthsModel *month = [self isMonth:indexPath];
    // 如果点击的是分组，则取当前状态的反并更新数据
    if (month) {
        HMMonthCell *cell = [tableView dequeueReusableCellWithIdentifier:@"monthCell" forIndexPath:indexPath];
        cell.model = month;
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        return cell;
    } else {
        HMNoteCell *cell = [tableView dequeueReusableCellWithIdentifier:@"noteCell" forIndexPath:indexPath];
        NoteModel *note = [self isNote:indexPath];
        cell.model = note;
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        return cell;
    }
    
}

//获取对应的note模型
- (NoteModel *)isNote:(NSIndexPath *)indexPath {
    NSUInteger num = -1;
    NSUInteger index = indexPath.row;
    // 获取点击的section
    HMMyNoteModel *model = [self.myNoteModelArray objectAtIndex:indexPath.section];
    // 获取section下的所有分组
    NSMutableArray *months = model.monthModels;
    
    for (MonthsModel *month in months) {
        num++;
        if (month.isDelop) {
            NSUInteger temp = num;
            num += [month.noteModels count];
            if (index <= num) {
                NSUInteger k = index - temp - 1;
                return [month.noteModels objectAtIndex:k];
            }
        }
    }
    return nil;
}

//判断点击不同cell有不同效果
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    MonthsModel *month = [self isMonth:indexPath];
    // 如果点击的是分组，则取当前状态的反并更新数据
    if (month) {
        month.isDelop = !month.isDelop;
        [self.handwritingTableView reloadData];
    } else {
        NoteModel *note = [self isNote:indexPath];
        HMEditViewController *editVC = [[HMEditViewController alloc] init];
        editVC.note = note;
        editVC.changeNote = ^(NSString *content,NSString *isPublic){
            note.content = content;
            note.isPublic = isPublic;
            [self.handwritingTableView reloadData];
        };
        [self.navigationController pushViewController:editVC animated:YES];
    }
}

//判断点击的cell是否是month
- (MonthsModel *)isMonth:(NSIndexPath *)indexPath {
    int num = -1;
    NSUInteger index = indexPath.row;
    
    HMMyNoteModel *year = [self.myNoteModelArray objectAtIndex:indexPath.section];
    NSMutableArray *months = year.monthModels;
    for (MonthsModel *month in months) {
        num++;
        if (index == num) {
            return month;
        }
        if (month.isDelop) {
            num += [month.noteModels count];
            if (index <= num) {
                return nil;
            }
        }
    }
    return nil;
}
//设置组头标题，也就是年份
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    HMMyNoteModel *model = [self.myNoteModelArray objectAtIndex:section];
    return model.year;
}


#pragma mark - 系统自带的一些方法的重写

//视图即将显示
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.editButton setHidden:NO];
}
//视图即将消失
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.editButton setHidden:YES];
}

#pragma mark - 一些属性的懒加载方法

//表格视图的懒加载方法
- (UITableView *)handwritingTableView {
    
    if (!_handwritingTableView) {
        _handwritingTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        _handwritingTableView.delegate = self;
        _handwritingTableView.dataSource = self;
        [_handwritingTableView setBounces:NO];
    }
    return _handwritingTableView;
}

//我的笔记模型数组初始化
- (NSMutableArray *)myNoteModelArray{
    if (!_myNoteModelArray) {
        
        _myNoteModelArray = [[NSMutableArray alloc] init];
        
    }
    return _myNoteModelArray;
}

//编辑按钮懒加载方法
- (UIButton *)editButton {
    if (!_editButton) {
        UIWindow *window = [[UIApplication sharedApplication] keyWindow];
        
        _editButton = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH * 0.8, SCREEN_HEIGHT * 0.8, 50, 50)];
        [window addSubview:_editButton];
        
        [_editButton setImage:[UIImage imageNamed:@"羽毛笔"] forState:(UIControlStateNormal)];
        [_editButton addTarget:self action:@selector(editBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _editButton;
}
//数据数组懒加载
- (NSMutableArray *)dictArr {
    if (!_dictArr) {
        _dictArr = [[NSMutableArray alloc] init];
    }
    return _dictArr;
}
//月份数组懒加载
- (NSArray *)monthStrArr {
    if (!_monthStrArr) {
        _monthStrArr = @[@"",@"一月",@"二月",@"三月",@"四月",@"五月",@"六月",@"七月",@"八月",@"九月",@"十月",@"十一月",@"十二月"];
    }
    return _monthStrArr;
}



@end
